package com.seu.vcampus.view;

import com.seu.vcampus.client.VCampusClient;
import com.seu.vcampus.util.UIStyleUtil;
import com.seu.vcampus.vo.User;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;

/**
 * 现代化个人信息面板
 * 显示和管理当前用户的个人信息
 * 
 * @author 虚拟校园开发团队
 * @since 2.0.0
 */
public class UserInfoPanel extends JPanel {
    private VCampusClient client;
    private User currentUser;
    
    // 用户信息字段
    private JTextField usernameField;
    private JTextField emailField;
    private JTextField phoneField;
    private JTextField userIdField;
    private JTextField userTypeField;
    private JTextField createTimeField;
    private JCheckBox activeCheckBox;
    
    // 操作按钮
    private JButton editButton;
    private JButton saveButton;
    private JButton cancelButton;
    private JButton changePasswordButton;
    
    // 状态标签
    private JLabel statusLabel;
    
    public UserInfoPanel(VCampusClient client, User user) {
        this.client = client;
        this.currentUser = user;
        
        UIStyleUtil.setupGlobalStyle();
        initializeComponents();
        setupLayout();
        setupEventHandlers();
        loadUserInfo();
    }
    
    /**
     * 初始化所有组件
     */
    private void initializeComponents() {
        setLayout(new BorderLayout());
        setBackground(UIStyleUtil.BACKGROUND_COLOR);
        setBorder(new EmptyBorder(20, 20, 20, 20));
        
        // 初始化字段（只读模式）
        userIdField = UIStyleUtil.createReadOnlyTextField();
        usernameField = UIStyleUtil.createReadOnlyTextField();
        emailField = UIStyleUtil.createReadOnlyTextField();
        phoneField = UIStyleUtil.createReadOnlyTextField();
        userTypeField = UIStyleUtil.createReadOnlyTextField();
        createTimeField = UIStyleUtil.createReadOnlyTextField();
        activeCheckBox = new JCheckBox("账户启用");
        activeCheckBox.setForeground(Color.BLACK);
        activeCheckBox.setEnabled(false);
        
        // 操作按钮
        editButton = UIStyleUtil.createPrimaryButton("编辑信息");
        saveButton = UIStyleUtil.createSuccessButton("保存修改");
        cancelButton = UIStyleUtil.createSecondaryButton("取消");
        changePasswordButton = UIStyleUtil.createWarningButton("修改密码");
        
        saveButton.setVisible(false);
        cancelButton.setVisible(false);
        
        // 状态标签
        statusLabel = UIStyleUtil.createModernLabel("就绪", UIStyleUtil.BODY_FONT, UIStyleUtil.SECONDARY_COLOR);
    }
    
    /**
     * 设置布局
     */
    private void setupLayout() {
        // 创建主面板
        JPanel mainPanel = UIStyleUtil.createCardPanel("个人信息");
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
        
        // 用户信息面板
        JPanel infoPanel = createInfoPanel();
        
        // 操作面板
        JPanel actionPanel = createActionPanel();
        
        // 状态面板
        JPanel statusPanel = createStatusPanel();
        
        mainPanel.add(infoPanel);
        mainPanel.add(Box.createVerticalStrut(20));
        mainPanel.add(actionPanel);
        mainPanel.add(Box.createVerticalStrut(10));
        mainPanel.add(statusPanel);
        
        add(mainPanel, BorderLayout.CENTER);
    }
    
    /**
     * 创建信息面板
     */
    private JPanel createInfoPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setOpaque(false);
        
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;
        
        // 第一列
        gbc.gridx = 0;
        gbc.gridy = 0;
        JLabel userIdLabel = new JLabel("用户ID:");
        userIdLabel.setForeground(Color.BLACK);
        panel.add(userIdLabel, gbc);
        
        gbc.gridy = 1;
        JLabel usernameLabel = new JLabel("用户名:");
        usernameLabel.setForeground(Color.BLACK);
        panel.add(usernameLabel, gbc);
        
        gbc.gridy = 2;
        JLabel emailLabel = new JLabel("邮箱:");
        emailLabel.setForeground(Color.BLACK);
        panel.add(emailLabel, gbc);
        
        gbc.gridy = 3;
        JLabel phoneLabel = new JLabel("电话:");
        phoneLabel.setForeground(Color.BLACK);
        panel.add(phoneLabel, gbc);
        
        gbc.gridy = 4;
        JLabel userTypeLabel = new JLabel("用户类型:");
        userTypeLabel.setForeground(Color.BLACK);
        panel.add(userTypeLabel, gbc);
        
        gbc.gridy = 5;
        JLabel createTimeLabel = new JLabel("创建时间:");
        createTimeLabel.setForeground(Color.BLACK);
        panel.add(createTimeLabel, gbc);
        
        gbc.gridy = 6;
        JLabel accountStatusLabel = new JLabel("账户状态:");
        accountStatusLabel.setForeground(Color.BLACK);
        panel.add(accountStatusLabel, gbc);
        
        // 第二列
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        panel.add(userIdField, gbc);
        
        gbc.gridy = 1;
        panel.add(usernameField, gbc);
        
        gbc.gridy = 2;
        panel.add(emailField, gbc);
        
        gbc.gridy = 3;
        panel.add(phoneField, gbc);
        
        gbc.gridy = 4;
        panel.add(userTypeField, gbc);
        
        gbc.gridy = 5;
        panel.add(createTimeField, gbc);
        
        gbc.gridy = 6;
        panel.add(activeCheckBox, gbc);
        
        return panel;
    }
    
    /**
     * 创建操作面板
     */
    private JPanel createActionPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 10));
        panel.setOpaque(false);
        
        panel.add(editButton);
        panel.add(saveButton);
        panel.add(cancelButton);
        panel.add(changePasswordButton);
        
        return panel;
    }
    
    /**
     * 创建状态面板
     */
    private JPanel createStatusPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        panel.setOpaque(false);
        panel.add(statusLabel);
        
        return panel;
    }
    
    /**
     * 设置事件处理器
     */
    private void setupEventHandlers() {
        editButton.addActionListener(e -> enableEditMode());
        saveButton.addActionListener(e -> saveChanges());
        cancelButton.addActionListener(e -> cancelEdit());
        changePasswordButton.addActionListener(e -> changePassword());
    }
    
    /**
     * 加载用户信息
     */
    private void loadUserInfo() {
        userIdField.setText(currentUser.getUserId());
        usernameField.setText(currentUser.getUsername());
        emailField.setText(currentUser.getEmail() != null ? currentUser.getEmail() : "未设置");
        phoneField.setText(currentUser.getPhone() != null ? currentUser.getPhone() : "未设置");
        userTypeField.setText(com.seu.vcampus.util.UserTypeUtil.getUserTypeText(currentUser.getUserType()));
        createTimeField.setText(currentUser.getCreateTime() != null ? 
                               currentUser.getCreateTime().toString() : "未知");
        activeCheckBox.setSelected(currentUser.isActive());
    }
    
    /**
     * 启用编辑模式
     */
    private void enableEditMode() {
        emailField.setEditable(true);
        phoneField.setEditable(true);
        
        editButton.setVisible(false);
        saveButton.setVisible(true);
        cancelButton.setVisible(true);
        changePasswordButton.setVisible(false);
        
        statusLabel.setText("编辑模式已启用");
    }
    
    /**
     * 保存修改
     */
    private void saveChanges() {
        String newEmail = emailField.getText().trim();
        String newPhone = phoneField.getText().trim();
        
        // 简单的输入验证
        if (!newEmail.isEmpty() && !isValidEmail(newEmail)) {
            JOptionPane.showMessageDialog(this, "请输入有效的邮箱地址", 
                                        "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        if (!newPhone.isEmpty() && !isValidPhone(newPhone)) {
            JOptionPane.showMessageDialog(this, "请输入有效的电话号码", 
                                        "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        // 更新用户信息
        currentUser.setEmail(newEmail.isEmpty() ? null : newEmail);
        currentUser.setPhone(newPhone.isEmpty() ? null : newPhone);
        
        // 这里应该发送到服务器保存
        // 现在只是显示成功消息
        JOptionPane.showMessageDialog(this, "个人信息更新成功", 
                                    "成功", JOptionPane.INFORMATION_MESSAGE);
        
        // 恢复只读模式
        disableEditMode();
    }
    
    /**
     * 取消编辑
     */
    private void cancelEdit() {
        // 重新加载原始信息
        loadUserInfo();
        disableEditMode();
    }
    
    /**
     * 禁用编辑模式
     */
    private void disableEditMode() {
        emailField.setEditable(false);
        phoneField.setEditable(false);
        
        editButton.setVisible(true);
        saveButton.setVisible(false);
        cancelButton.setVisible(false);
        changePasswordButton.setVisible(true);
        
        statusLabel.setText("就绪");
    }
    
    /**
     * 修改密码
     */
    private void changePassword() {
        JPasswordField currentPasswordField = new JPasswordField(20);
        JPasswordField newPasswordField = new JPasswordField(20);
        JPasswordField confirmPasswordField = new JPasswordField(20);
        
        JPanel panel = new JPanel(new GridLayout(0, 1));
        panel.add(new JLabel("当前密码:"));
        panel.add(currentPasswordField);
        panel.add(new JLabel("新密码:"));
        panel.add(newPasswordField);
        panel.add(new JLabel("确认新密码:"));
        panel.add(confirmPasswordField);
        
        int result = JOptionPane.showConfirmDialog(this, panel, "修改密码", 
                                                  JOptionPane.OK_CANCEL_OPTION);
        
        if (result == JOptionPane.OK_OPTION) {
            String currentPassword = new String(currentPasswordField.getPassword());
            String newPassword = new String(newPasswordField.getPassword());
            String confirmPassword = new String(confirmPasswordField.getPassword());
            
            if (newPassword.length() < 6) {
                JOptionPane.showMessageDialog(this, "密码长度至少6位", 
                                            "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            if (!newPassword.equals(confirmPassword)) {
                JOptionPane.showMessageDialog(this, "两次输入的新密码不一致", 
                                            "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // 这里应该发送到服务器验证和保存
            JOptionPane.showMessageDialog(this, "密码修改功能将在后续版本实现", 
                                        "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }
    
    /**
     * 验证邮箱格式
     */
    private boolean isValidEmail(String email) {
        return email.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");
    }
    
    /**
     * 验证电话号码格式
     */
    private boolean isValidPhone(String phone) {
        return phone.matches("^1[3-9]\\d{9}$");
    }
    
    /**
     * 获取用户类型文本
     * @deprecated 使用UserTypeUtil.getUserTypeText()代替
     */
    @Deprecated
    private String getUserTypeText(com.seu.vcampus.vo.User.UserType type) {
        return com.seu.vcampus.util.UserTypeUtil.getUserTypeText(type);
    }
}